{include file="layout/layui_header" /}

<!-- 主要内容 -->
<div class="main-content">
    <div class="page-header">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统用户账号和权限</p>
    </div>

<style>
.layui-card { 
    margin-bottom: 15px; 
    box-shadow: 0 1px 2px rgba(0,0,0,0.15);
}
.stat-item { 
    text-align: center; 
    padding: 20px; 
}
.stat-value { 
    font-size: 32px; 
    font-weight: bold; 
    color: #01AAED; 
}
.stat-label { 
    margin-top: 8px; 
    color: #666; 
}
.user-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
}
.user-title {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
}
.user-actions {
    display: flex;
    gap: 8px;
}
.search-form {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 15px;
    border: 1px solid #e6e8eb;
}
.search-form .layui-form-item {
    margin-bottom: 0;
}
.search-inline {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: end;
}
.search-inline .layui-inline {
    margin: 0;
}
.table-container {
    margin-top: 0;
}
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 用户统计概览 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>用户概览</h3>
                </div>
                <div class="layui-card-body">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="totalUsers">0</div>
                                <div class="stat-label">总用户数</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="onlineUsers">0</div>
                                <div class="stat-label">当前在线</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="adminUsers">0</div>
                                <div class="stat-label">管理员</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="disabledUsers">0</div>
                                <div class="stat-label">已禁用</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 用户列表 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <div class="user-header">
                        <h3 class="user-title">用户列表</h3>
                        <div class="user-actions">
                            <button class="layui-btn layui-btn-normal" onclick="addUser()">
                                <i class="layui-icon layui-icon-add-1"></i> 添加用户
                            </button>
                            <button class="layui-btn layui-btn-primary" onclick="refreshTable()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索表单 -->
                    <div class="search-form">
                        <div class="layui-form">
                            <div class="search-inline">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 60px;">用户名</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="searchUsername" class="layui-input" placeholder="请输入用户名">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 70px;">真实姓名</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="searchRealName" class="layui-input" placeholder="请输入真实姓名">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 50px;">状态</label>
                                    <div class="layui-input-inline" style="width: 120px;">
                                        <select name="searchStatus">
                                            <option value="">全部</option>
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn" onclick="searchUsers()">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button class="layui-btn layui-btn-primary" onclick="resetSearch()">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 数据表格 -->
                    <div class="table-container">
                        <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<!-- 操作按钮模板 -->
<script type="text/html" id="userBarDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="resetPwd">重置密码</a>
    {{# if(d.id != 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    {{# } }}
</script>

{include file="layout/layui_footer" /}

<script>
layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;

    // 初始化表格
    table.render({
        elem: '#userTable',
        url: '/admin/settings/getUserList',
        height: 'full-200',
        page: true,
        loading: true,
        parseData: function(res) {
            // 更新统计数据
            if (res.data && res.data.length > 0) {
                updateStats(res.data, res.count);
            }
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count,
                "data": res.data
            };
        },
        cols: [[
            {field: 'username', title: '用户名', width: 120, fixed: 'left'},
            {field: 'real_name', title: '真实姓名', width: 120},
            {field: 'email', title: '邮箱', width: 180},
            {field: 'phone', title: '手机号', width: 130},
            {field: 'department', title: '部门', width: 120},
            {field: 'position', title: '职位', width: 120},
            {field: 'role_names', title: '角色', width: 150},
            {field: 'status', title: '状态', width: 80, templet: function(d){
                return d.status == 1 ? '<span style="color: #5FB878;">启用</span>' : '<span style="color: #FF5722;">禁用</span>';
            }},
            {field: 'last_login_time', title: '最后登录', width: 160},
            {field: 'created_at', title: '创建时间', width: 160},
            {title: '操作', width: 200, toolbar: '#userBarDemo', fixed: 'right'}
        ]]
    });

    // 监听工具条
    table.on('tool(userTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            editUser(data.id);
        } else if(obj.event === 'del'){
            deleteUser(data.id, data.username);
        } else if(obj.event === 'resetPwd'){
            resetPassword(data.id, data.username);
        }
    });

    // 更新统计数据
    function updateStats(data, total) {
        var online = 0, admin = 0, disabled = 0;
        
        data.forEach(function(user) {
            if (user.status == 0) disabled++;
            if (user.role_names.indexOf('管理员') >= 0 || user.role_names.indexOf('超级管理员') >= 0) admin++;
            // 这里可以根据实际需求判断在线状态
        });
        
        $('#totalUsers').text(total);
        $('#onlineUsers').text(online);
        $('#adminUsers').text(admin);
        $('#disabledUsers').text(disabled);
    }

    // 搜索用户
    window.searchUsers = function() {
        table.reload('userTable', {
            where: {
                username: $('input[name="searchUsername"]').val(),
                real_name: $('input[name="searchRealName"]').val(),
                status: $('select[name="searchStatus"]').val()
            }
        });
    };

    // 重置搜索
    window.resetSearch = function() {
        $('input[name="searchUsername"]').val('');
        $('input[name="searchRealName"]').val('');
        $('select[name="searchStatus"]').val('');
        form.render('select');
        table.reload('userTable', {
            where: {}
        });
    };

    // 刷新表格
    window.refreshTable = function() {
        table.reload('userTable');
    };

    // 添加用户
    window.addUser = function() {
        // 先获取角色列表
        $.get('/admin/settings/getAllRoles', function(res) {
            if (res.code === 0) {
                var roleOptions = '';
                res.data.forEach(function(role) {
                    roleOptions += '<option value="' + role.id + '">' + role.role_name + '</option>';
                });
                
                showUserForm('添加用户', {}, roleOptions);
            } else {
                layer.msg('获取角色列表失败：' + res.msg, {icon: 2});
            }
        });
    };

    // 编辑用户
    window.editUser = function(id) {
        // 获取用户详情和角色列表
        $.when(
            $.get('/admin/settings/getUserDetail', {id: id}),
            $.get('/admin/settings/getAllRoles')
        ).done(function(userRes, roleRes) {
            if (userRes[0].code === 0 && roleRes[0].code === 0) {
                var user = userRes[0].data;
                var roleOptions = '';
                roleRes[0].data.forEach(function(role) {
                    var selected = user.role_ids.indexOf(role.id) >= 0 ? 'selected' : '';
                    roleOptions += '<option value="' + role.id + '" ' + selected + '>' + role.role_name + '</option>';
                });
                
                showUserForm('编辑用户', user, roleOptions);
            } else {
                layer.msg('获取用户信息失败', {icon: 2});
            }
        });
    };

    // 显示用户表单
    function showUserForm(title, user, roleOptions) {
        var isEdit = user.id ? true : false;
        var html = '<div style="padding: 20px;">' +
            '<form class="layui-form" lay-filter="userForm">' +
            (isEdit ? '<input type="hidden" name="id" value="' + user.id + '">' : '') +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">用户名 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="username" lay-verify="required" placeholder="请输入用户名" class="layui-input" value="' + (user.username || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">真实姓名 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="real_name" lay-verify="required" placeholder="请输入真实姓名" class="layui-input" value="' + (user.real_name || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">密码' + (isEdit ? '' : ' <span style="color:red;">*</span>') + '</label>' +
                '<div class="layui-input-block">' +
                    '<input type="password" name="password" ' + (isEdit ? '' : 'lay-verify="required"') + ' placeholder="' + (isEdit ? '留空表示不修改密码' : '请输入密码') + '" class="layui-input">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">邮箱</label>' +
                '<div class="layui-input-block">' +
                    '<input type="email" name="email" placeholder="请输入邮箱" class="layui-input" value="' + (user.email || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">手机号</label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="phone" placeholder="请输入手机号" class="layui-input" value="' + (user.phone || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">部门</label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="department" placeholder="请输入部门" class="layui-input" value="' + (user.department || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">职位</label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="position" placeholder="请输入职位" class="layui-input" value="' + (user.position || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色</label>' +
                '<div class="layui-input-block">' +
                    '<select name="role_ids" multiple>' +
                        roleOptions +
                    '</select>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">状态</label>' +
                '<div class="layui-input-block">' +
                    '<select name="status">' +
                        '<option value="1" ' + (user.status == 1 ? 'selected' : '') + '>启用</option>' +
                        '<option value="0" ' + (user.status == 0 ? 'selected' : '') + '>禁用</option>' +
                    '</select>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                    '<button type="submit" class="layui-btn" lay-submit lay-filter="submitUser">保存</button>' +
                    '<button type="reset" class="layui-btn layui-btn-primary">重置</button>' +
                '</div>' +
            '</div>' +
            '</form>' +
            '</div>';

        layer.open({
            type: 1,
            title: title,
            content: html,
            area: ['600px', '680px'],
            success: function(layero, index) {
                form.render();
                
                // 监听表单提交
                form.on('submit(submitUser)', function(data) {
                    var url = isEdit ? '/admin/settings/editUser' : '/admin/settings/addUser';
                    
                    $.post(url, data.field, function(res) {
                        if (res.code === 0) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                            table.reload('userTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    });
                    
                    return false;
                });
            }
        });
    }

    // 删除用户
    window.deleteUser = function(id, username) {
        layer.confirm('确定要删除用户 "' + username + '" 吗？', function(index) {
            $.post('/admin/settings/deleteUser', {id: id}, function(res) {
                if (res.code === 0) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('userTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
                layer.close(index);
            });
        });
    };

    // 重置密码
    window.resetPassword = function(id, username) {
        layer.confirm('确定要重置用户 "' + username + '" 的密码吗？', function(index) {
            $.post('/admin/settings/resetPassword', {id: id}, function(res) {
                if (res.code === 0) {
                    layer.msg(res.msg, {icon: 1, time: 3000});
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
                layer.close(index);
            });
        });
    };
});
</script> 